package com.own.business.system.user.phone.controller;

import com.own.business.login.phone.controller.LoginPhoneController;
import com.own.business.login.phone.core.form.LoginPhoneForm;
import com.own.business.system.user.business.service.SystemUserInfoService;
import com.own.business.system.user.common.exception.SystemUserException;
import com.own.business.system.user.phone.business.service.SystemUserPhoneLoginService;
import com.own.component.common.login.util.SessionUserUtil;
import com.own.component.common.model.R;
import com.own.component.common.model.ResultModel;
import com.own.component.log.operation.aop.LogOperationAop;
import com.own.component.sms.core.util.code.SmsCodeUtil;
import com.own.constant.ConstantApiPrefix;
import com.own.constant.ConstantBeanSuffix;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * SystemUserPhoneLoginController
 *
 * @author chenxueli
 * @date 2023-06-25 23:16:31
 */
@Slf4j
@Tag(name = "手机登录模块" + ConstantBeanSuffix.CONTROLLER)
@RestController
@RequestMapping(ConstantApiPrefix.BASE_API_V1_PREFIX + "system/user/phone/login")
public class SystemUserPhoneLoginController extends LoginPhoneController {

    @Resource
    private SystemUserPhoneLoginService systemUserPhoneLoginService;

    @Resource
    private SystemUserInfoService systemUserInfoService;

    @Resource
    private SmsCodeUtil smsCodeUtil;

    @LogOperationAop
    @Operation(summary = "绑定手机号")
    @PostMapping("/bind")
    public ResultModel<Boolean> bind(@RequestBody LoginPhoneForm form) {
        return changeBind(form);
    }

    @LogOperationAop
    @Operation(summary = "换绑手机号")
    @PostMapping("/change/bind")
    public ResultModel<Boolean> changeBind(
            @RequestBody LoginPhoneForm form
    ) {
        var loginUser = SessionUserUtil.getLoginUser();
        form.check();
        var model = smsCodeUtil.verification(form.getPhone(), form.getKey(), form.getCode());
        if (!model.success()) {
            throw new SystemUserException("验证码不正确");
        }
        var phone = model.phone();
        // 获取token
        systemUserPhoneLoginService.changeBind(loginUser.userId(), phone);
        // 修改用户的手机号信息
        systemUserInfoService.updatePhone(loginUser.userId(), phone);
        // 返回信息
        return R.success(true, "绑定成功");
    }

    @LogOperationAop
    @Operation(summary = "解绑手机号")
    @PostMapping("/unbind")
    public ResultModel<Boolean> unbind() {
        var loginUser = SessionUserUtil.getLoginUser();
        systemUserPhoneLoginService.unbind(loginUser.userId());
        return R.success(true, "解绑成功");
    }

}
